<template>
  <div class="register">
    <el-card style="width: 400px; border-radius: 10px; padding: 30px;">
      <h3 style="text-align: center; margin-bottom: 20px;">SCM供应链管理系统</h3>

      <el-form ref="ruleFormRef" :model="addForm" :rules="rules" label-width="100px" status-icon class="demo-addForm">
        <el-form-item label="公司名称" prop="name">
          <el-input prefix-icon="OfficeBuilding" v-model="addForm.name" />
        </el-form-item>

        <el-form-item label="公司编号" prop="code">
          <el-input prefix-icon="OfficeBuilding" v-model="addForm.code" />
        </el-form-item>

        <el-form-item label="公司法人" prop="legalPerson">
          <el-input prefix-icon="User" v-model="addForm.legalPerson" />
        </el-form-item>

        <el-form-item label="联系人方式" prop="phone">
          <el-input prefix-icon="PhoneFilled" v-model="addForm.phone" />
        </el-form-item>

        <el-form-item label="身份证号码" prop="idCard">
          <el-input prefix-icon="Postcard" v-model="addForm.idCard" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 省市区级联 -->
        <el-form-item label="省 / 市 / 区" prop="region">
          <el-cascader v-model="addForm.region" :options="regionData" placeholder="请选择省市区" style="width: 100%"
            size="small" clearable filterable @change="handleRegionChange" />
        </el-form-item>

        <!-- 详细地址 -->
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addForm.detailAddress" placeholder="街道、门牌号、楼栋等" size="small" @input="updateFullAddress" />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item label="验证码" prop="verificationCode">
          <el-row :gutter="10">
            <el-col :span="16">
              <el-input v-model="addForm.verificationCode" placeholder="请输入验证码" prefix-icon="Message" />
            </el-col>
            <el-col :span="8">
              <el-button type="primary" :disabled="!canSendCode" @click="sendVerificationCode" style="width: 100%;"
                :loading="sending">
                {{ countDown > 0 ? `${countDown}s 后重发` : '获取验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button style="width: 100%;" type="primary" @click="submitForm" :loading="registering">
            注册
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import axios from 'axios'
import { reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'

const ruleFormRef = ref()
const router = useRouter()
const sending = ref(false)
const registering = ref(false)

// 倒计时
const countDown = ref(0)

// // 地址数据
// const form = reactive({
//   region: [],
//   detailAddress: ''
// })

// 表单数据（字段名必须和模板一致！）
const addForm = reactive({
  name: '',           // 公司名称
  code: '',           // 公司编号
  legalPerson: '',    // 公司法人
  phone: '',          // 联系电话
  idCard: '',         // 身份证号
  sex: '1',           // 性别，默认男
  region: [],
  detailAddress: '',
  address: '',         // 完整地址：省市区 + 详细地址
  verificationCode: '' // 验证码
})

// 安全处理地区选择变化
const handleRegionChange = (value) => {
  try {
    addForm.region = Array.isArray(value) ? value : []
    updateFullAddress()
  } catch (error) {
    console.error('处理地区选择变化失败:', error)
    addForm.region = []
  }
}

// 安全更新完整地址
const updateFullAddress = () => {
  try {
    const { region, detailAddress } = addForm

    addForm.address = detailAddress || ''

    if (!region || region.length !== 3) {
      return
    }

    const provinceCode = region[0]
    const cityCode = region[1]
    const districtCode = region[2]

    if (!provinceCode || !cityCode || !districtCode) {
      return
    }

    const province = codeToText[provinceCode] || ''
    const city = codeToText[cityCode] || ''
    const district = codeToText[districtCode] || ''

    if (!province || !city || !district) {
      return
    }

    const regionText = `${province} ${city} ${district}`
    addForm.address = detailAddress ?
      `${regionText} ${detailAddress}`.trim() : regionText

  } catch (error) {
    console.error('生成完整地址失败:', error)
    addForm.address = addForm.detailAddress || ''
  }
}

// 手机号正则
const phonePattern = /^1[3-9]\d{9}$/

// 身份证号简单校验（可按需增强）
const idCardPattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/

const checkName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('用户名不能为空'))
  } else {
    callback()
  }
}

const checkCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error('公司编码不能为空'))
  } else {
    callback()
  }
}

const checkLegalPerson = (rule, value, callback) => {
  if (!value) {
    callback(new Error('联系人不能为空'))
  } else {
    callback()
  }
}

const checkPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('联系电话不能为空'))
  } else if (!phonePattern.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}

const checkIdCard = (rule, value, callback) => {
  if (!value) {
    callback(new Error('身份证号码不能为空'))
  } else if (!idCardPattern.test(value)) {
    callback(new Error('身份证号码格式不正确'))
  } else {
    callback()
  }
}

const checkVerificationCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error('验证码不能为空'))
  } else {
    callback()
  }
}

const checkRegion = (rule, value, callback) => {
  if (!Array.isArray(value) || value.length !== 3) {
    callback(new Error('请选择完整的省 / 市 / 区'))
  } else {
    callback()
  }
}

const checkDetailAddress = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入详细地址'))
  } else {
    callback()
  }
}


// 验证规则
const rules = reactive({
  name: [{ validator: checkName, trigger: 'blur' }],
  code: [{ validator: checkCode, trigger: 'blur' }],
  legalPerson: [{ validator: checkLegalPerson, trigger: 'blur' }],
  phone: [{ validator: checkPhone, trigger: 'blur' }],
  idCard: [{ validator: checkIdCard, trigger: 'blur' }],
  region: [{ validator: checkRegion, trigger: 'change' }],
  detailAddress: [{ validator: checkDetailAddress, trigger: 'blur' }],
  verificationCode: [{ validator: checkVerificationCode, trigger: 'blur' }],
})

// 是否可以发送验证码（手机号合法 + 不在倒计时）
const canSendCode = computed(() => {
  return phonePattern.test(addForm.phone) && countDown.value === 0 && !sending.value
})

// 发送验证码
const sendVerificationCode = async () => {
  if (!canSendCode.value) return
  sending.value = true

  console.log('向手机号发送验证码:', addForm.phone)

  try {
    const res = await axios.get('/api/basic/auth/sendVerifyCode', { params: { phone: addForm.phone } })
    if (res.data.code === 5200) {
      // 启动倒计时
      countDown.value = 60
      const timer = setInterval(() => {
        if (countDown.value > 0) {
          countDown.value--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    ElMessage.error(error.message || '验证码发送失败')

  } finally {
    sending.value = false
  }
}

// 提交表单
const submitForm = () => {
  // 先校验 Element 表单字段（名称、电话等）
  ruleFormRef.value?.validate((valid) => {
    if (!valid) return
    
    doRegister()
  })
}

const doRegister = async () => {
  registering.value = true
  const company = { ...addForm }


  try {
    const res = await axios.post('/api/basic/auth/register', company)
    if (res.data.code === 5200) {
      ElMessage.success('注册成功')
      router.push({ name: 'login' })
    } else {
      ElMessage.error(res.data.msg || '注册失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    registering.value = false
  }
}
</script>

<style scoped>
.register {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}
</style>